package com.boat.starter.jetcache.util;

import com.alicp.jetcache.CacheValueHolder;
import com.alicp.jetcache.support.AbstractValueDecoder;
import com.alicp.jetcache.support.AbstractValueEncoder;
import com.alicp.jetcache.support.FastjsonKeyConvertor;
import com.alicp.jetcache.support.JavaValueDecoder;
import com.alicp.jetcache.support.JavaValueEncoder;

import lombok.extern.slf4j.Slf4j;

/**
 * 缓存序列化工具
 * 
 * @author 周江
 *
 */
@Slf4j
public class SerializationUtils {
	public static FastjsonKeyConvertor KEY_SERIALIZER = FastjsonKeyConvertor.INSTANCE;
	public static AbstractValueEncoder VALUE_SERIALIZER = JavaValueEncoder.INSTANCE;
	public static AbstractValueDecoder VALUE_DESERIALIZER = JavaValueDecoder.INSTANCE;

	/*
	 * key序列化
	 */
	public static String serializeOfKey(Object originalKey) {
		return (String) KEY_SERIALIZER.apply(originalKey);
	}

	/**
	 * value序列化
	 * 
	 * @param value
	 * @return
	 */
	public static byte[] serializeOfValue(Object value) {
		return VALUE_SERIALIZER.apply(value);
	}

	/**
	 * value反系列化为java对象
	 * 
	 * @param <T>
	 * @param objectData
	 * @return
	 */
	public static <T> T deserializeOfValue(byte[] objectData) {
		try {
			final T obj = (T) VALUE_DESERIALIZER.apply(objectData);
			return obj;
		} catch (ClassCastException ex) {
			// 对于使用CacheUtil设置值，RedisUtils获取值时会出现类型转换问题，下面代码对两个类混用问题进行兼容
			if (log.isDebugEnabled()) {
				log.debug("发生缓存类型转换错误：{}。当使用RedisUtils.get获取CacheUtil设置的值时会出现问题。已做兼容性处理", ex.getMessage());
			}
			CacheValueHolder holder = (CacheValueHolder) VALUE_DESERIALIZER.apply(objectData);
			@SuppressWarnings("unchecked")
			final T obj = (T) holder.getValue();
			return obj;
		}
	}
}
